package midalgorithms.sortandsearch;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class _02topKFrequent {
    public static int[] topKFrequent(int[] nums, int k) {
        //  建立哈希表
        int[] res = new int[k];
        HashMap<Integer,Integer> hashMap = new HashMap<>();
        for (int i = 0;i < nums.length;i++){
            hashMap.put(nums[i],hashMap.getOrDefault(nums[i],0)+1);
        }
        //  查找value值最多的前k项数据
        int index = 0;
        while (index < k){
            Iterator<Integer> iterator = hashMap.keySet().iterator();
            int maxVal = 0,maxKey = 0;
            while (iterator.hasNext()){
                Integer nowKey = iterator.next();
                if (hashMap.get(nowKey) > maxVal){
                    maxKey = nowKey;
                    maxVal = hashMap.get(nowKey);
                }
            }
            //  当前哈希表value最大元素就是maxKey
            res[index++] = maxKey;
            hashMap.remove(maxKey);
        }
        return res;
    }
}
